import requests
import os
import sys
from urllib.parse import urlparse

def wget_download(url, output_path=None):
    """
    使用wget方式下载文件
    
    Args:
        url (str): 下载链接
        output_path (str, optional): 输出文件路径
    
    Returns:
        str: 下载文件的路径
    """
    try:
        # 发送HTTP请求
        response = requests.get(url, stream=True)
        response.raise_for_status()
        
        # 获取文件名
        if output_path is None:
            parsed_url = urlparse(url)
            filename = os.path.basename(parsed_url.path)
            if not filename:
                filename = "downloaded_file"
            output_path = filename
        
        # 写入文件
        with open(output_path, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)
        
        print(f"文件已下载至: {output_path}")
        return output_path
        
    except requests.exceptions.RequestException as e:
        print(f"下载失败: {e}")
        return None
    except IOError as e:
        print(f"文件写入失败: {e}")
        return None

def main():
    """
    主函数，处理命令行参数
    """
    if len(sys.argv) < 2:
        print("使用方法: python wget_file.py <下载链接> [输出文件名]")
        return
    
    url = sys.argv[1]
    output_path = sys.argv[2] if len(sys.argv) > 2 else None
    
    wget_download(url, output_path)

if __name__ == "__main__":
    main()